<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('materials.outboundOrder')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('hardwareOut.barcodeInformation') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('hardwareOut.returnDepartment') }}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.peportmentList"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text"
							v-model="data.department" @select="departmentSelect"></superweiCombox>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;" v-show="false">
						<text class="item-info-title">{{ $t('hardwareOut.returner') }}：</text>
						<chooseSelect style="text-align:right;" :requestUrl="'/wms/sysUser/getPageSet'" :row="'2'"
							:placeholder="$t('materials.requisitionPerson')" :isJSON="true" keyName="text"
							v-model="data.userName" @setClick="chooseSelectItem"></chooseSelect>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('materials.expenseItem') }}：</text>
						<chooseSelect style="text-align: right;" :row="'1'" :requestUrl="'/wms/sysUser/getPageCostItemSet'"
							:placeholder="$t('materials.selectAFee')" :isJSON="true" keyName="text" v-model="data.costItem"
							@setClick="chooseSelectCostItem"></chooseSelect>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;" v-if="false">
						<text class="item-info-title">{{ $t('materials.generateReturnNote') }}：</text>
						<view class="gui-form-body gui-text-right" style="overflow:visible;">
							<superweiCombox style="text-align:right;" :candidates="data.selectList"
								:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="name"
								@select="select" v-model="data.selectIdText" :defaultValue="$t('index.no')">
							</superweiCombox>
						</view>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{ $t('materials.remark') }}：</text>
						<input type="text" v-model="data.remark" class="gui-form-input gui-text-right"
							:placeholder="$t('materials.pleaseRemarks')" />
					</view>
					<view class="custom-card-itemTwo " style="padding: 20rpx 0">
						<text class="required-color"
								style="padding-right: 20rpx">*</text>
						<view class="card-item-50 checkbox">
							<checkbox-group @change="checkboxAllChange()">
								<checkbox class="checkbox-check" :checked="data.checkAll === true"
									placeholder-style="color:#fff" style="color: #fff;" />
							</checkbox-group>
							<text class="gui-text-small checkbox-spec">{{ $t('smashRemoval.all') }}</text>
						</view>
						<view class="card-item-50 checkbox">
							<checkbox-group @change="checkboxPartChange()">
								<checkbox class="checkbox-check" :checked="data.checkPart === true"
									placeholder-style="color:#fff" style="color: #fff;" />
							</checkbox-group>
							<text class="gui-text-small checkbox-spec">{{ $t('Common.part') }}</text>
						</view>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">{{ $t('distributedEnter.barcodeScan')
						}}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue" type="search"
							:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm"
							@iconClick="iconClick"></uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0">
						<text class="item-info-title" style="padding-right: 40rpx"><text class="required-color"
								style="padding-right: 6rpx">*</text>{{ $t('hardwareOut.returnedQty') }}：</text>
						<uni-easyinput disabled class="uni-mt-5" type="number" v-model="data.allInputNum">
						</uni-easyinput>
						<!-- <view class="card-checkBtn bottomBtn-bgcolor-green" @click="confirm">确定</view> -->
					</view>
				</view>
				<!-- card模块 -->
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<view class="custom-form-card">
					<uni-collapse v-if="data.scanInfo" v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{$t('distributedOut.barcode')}}：</text>{{ data.scanInfo.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
											data.scanInfo.materialCode }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
											data.scanInfo.materialName }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
										data.scanInfo.materialSpec || '' }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.qty') }}：</text>{{
											data.scanInfo.currentQty }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('hardwareOut.outQty') }}：</text>{{
											data.scanInfo.inputNum }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{
											data.scanInfo.unit }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelSubmit">
						{{ $t('materials.outgoingWarehouses') }}</view>
				</view>
			</view>
			<!-- 弹框填写数量 -->
			<uni-popup ref="inputDialog" type="center">
				<view v-if="data.scanInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}:{{ data.scanInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}:{{ data.scanInfo.materialName }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialSpec') }}:{{ data.scanInfo.materialSpec || '' }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.uom') }}:{{ data.scanInfo.unit }}
						</view>
						<!-- <view class="input-dialog-item">
							{{ $t('JsInternational.ofStock') }}:{{ data.scanInfo.currentQty }}
						</view> -->
						<view class="gui-form-item" style="color: #dd524d">
							<text style="width:210rpx;">{{ $t('hardwareOut.returnedQty') }}：</text>
							<view>
								<input type="number" style="margin: 8rpx 0;" class="gui-form-input" :disabled="!data.checkPart"
									v-model="data.scanInfo.inputNum" :placeholder="$t('materials.pleaseEnterThes')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import superweiCombox from '@/components/superweiCombox';
import chooseSelect from '@/components/chooseSelect';
import { getDataDictionaryFn, pitchOnFn2 } from '@/utils/index.js'
import { useStore } from "vuex";  //vuex存储的数据
import pdaScan from '@/hooks/pdaScan.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'
import {
	ref,
	reactive,
	onMounted,
	watch,
	computed,
	toRaw
} from 'vue';
import { iqcOutCommits, wmsSelectWmsBarcodeInfo } from '@/api/api.js'

//JS国际化引入
import { useI18n } from 'vue-i18n';
import { onBackPress } from '@dcloudio/uni-app';
components: {
	superweiCombox,
		chooseSelect
}
const { t } = useI18n();

let store = useStore();
//页面弹框输入数量使用的变量
let inputDialog = ref(null)
const { scan } = pdaScan()
let data = reactive({
	costItem: '',//费用项目
	remark: '',//备注
	userName: '',//领料人
	allInputNum: null,//总数量
	value: ['0'],
	iqcOutScanListOther: [],//扫描存储数组
	warehouseName: '',// 仓库
	scanInfo: undefined, // 当前扫描信息
	locationCode: '',// 库位
	peportmentList: [],//领料人数组
	peportmentList2: [],
	deportmentCode: '', //领料部code
	department: '', //领料部门
	scanValue: '',//扫码信息
	inputNum: null,//数量
	selectList: [{
		id: 'Y',
		name: t('index.yes')
	}, {
		id: "N",
		name: t('index.no')
	}],// 校验状态数组
	selectIdText: t('index.yes'),
	selectId: "Y",
	checkPart: false,
	checkAll: true
});
onMounted(() => {
	// 获取库位
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	getInitData()
})

// 是否生成退货单
const select = (e) => {
	data.selectId = e.id;
}


const getInitData = async () => {
	// 获取领料人数据
	data.peportmentList = await getDataDictionaryFn('Deportment')
	// // 只获取部门为品管部
	// Object.values(data.peportmentList).forEach(key=>{
	// 	if(key.selected){
	// 		console.log(key)
	// 		data.peportmentList2={0:key}
	// 	}
	// })
	let tepSelect1 = pitchOnFn2(data.peportmentList)
	if (tepSelect1.length == 0) return
	console.log(tepSelect1)
	data.department = tepSelect1[0].text // 默认选中第一个 text
	data.deportmentCode = tepSelect1[0].value  // 默认选中第一个 value
}
// 监听手动赋值
const computeData = () => {
	data.allInputNum = null
	if (!data.scanInfo && data.iqcOutScanListOther.length > 0) {
		data.scanInfo = data.iqcOutScanListOther[0]
	}
	if (data.scanInfo && data.iqcOutScanListOther.length == 0) {
		data.scanInfo = undefined
		data.inputNum = null
	}
	data.iqcOutScanListOther.forEach(element => {
		data.allInputNum += Number(element.inputNum)
	});
}
// vuex 计算添加
data.iqcOutScanListOther = computed(() => {
	return store.state.hardWare.iqcOutScanListOther
})
// 监听returnSpScanList变化
watch(() => data.iqcOutScanListOther, () => {
	computeData()
}, {
	immediate: true,
	deep: true
});
//监听当前扫描信息的变化
watch(() => data.scanInfo, (newVal) => {
	if (!newVal) {
		data.warehouseName = ''
		data.locationCode = ''
		data.inputNum = null
	} else {
		data.warehouseName = newVal.warehouseName
		data.locationCode = newVal.locationCode
	}
}, {
	immediate: true,
	deep: true
});
// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
const chooseSelectItem = (e) => {
	data.userName = e.userName
}
const chooseSelectCostItem = (e) => {
	data.costItem = e.Name
}
// 弹框的取消按钮
const cancelFn = () => {
	data.scanInfo = undefined
	inputDialog.value.close()
}
//弹框的确定按钮
const confirmFn = () => {
	if(data.scanInfo.inputNum==0 || data.scanInfo.inputNum>data.scanInfo.currentQty){
		uni.showToast({ title: t('Common.inputNumber'), icon: "none" });
		return
	}
	if (data.scanInfo.inputNum == null) {
		// t('JsInternational.plsReturn')
		uni.showToast({ title: t('materials.pleaseEnterThe'), icon: "none" });
		return
	}
	// if (data.scanInfo.inputNum > data.scanInfo.currentQty) {
	// 	// t('JsInternational.plsReturn')
	// 	uni.showToast({ title: t('materials.understock'), icon: "none" });
	// 	data.scanInfo.inputNum = null
	// 	return
	// }
	// t('JsInternational.qtyCant')
	if (Number(data.scanInfo.inputNum) <= 0) {
		uni.showToast({ title: t('materials.outgoingQuantityCannot'), icon: "none" });
		return
	}
	store.dispatch('hardWare/setIqcOutScanListOther', data.scanInfo)
	uni.showToast({ title: t('JsInternational.dataSaved'), icon: "none" });
	inputDialog.value.close();
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	let arr = data.iqcOutScanListOther.filter(x => x.barcode == code)
	if (arr.length > 0) {
		uni.showToast({ title: t('JsInternational.repeatTo'), icon: "none" });
		return
	}
	// if (!data.userName.length) {
	// 	uni.showToast({ title: t('materials.requisitionPerson'), icon: "none" });
	// 	return
	// }
	data.scanValue = code
	let parmes = {
		barcode: code,
		selectType: 'iqcOut',
		receiptId: data.id,
		isSp: 1,
	}
	wmsSelectWmsBarcodeInfo(parmes).then(res => { //接口
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '粉碎简单生产退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.status == 200) {
			// 判断是否为国外条码，是全部粉碎，不是就可以部分
			// if(data.checkPart&&(res.data.qrCode==null|| res.data.qrCode=='')){
			// 	uni.showToast({ title: t('warehousing.completelyCrushed'), icon: "none" });
			// 	return
			// }
			data.scanInfo = res.data
			//判断是不是不同的物料
			if (data.iqcOutScanListOther != null && data.iqcOutScanListOther.length > 0) {
				var materialArr = data.iqcOutScanListOther.filter(e => e.materialCode == res.data.materialCode)
				if (!materialArr.length) {
					uni.showToast({ title: 'Only one material can be scanned', icon: "none" });
					return
				}
			}
			// if(res.data!=null&&res.data.attribute3!=null&&!isNaN(res.data.attribute3))
			// {
			// 	 var attribute3=parseFloat(res.data.attribute3)
			// 	 if(attribute3>=res.data.currentQty)
			// 	 {
			// 		 data.scanInfo.inputNum = attribute3-res.data.currentQty
			// 	 }
			// 	 else{
			// 		 data.scanInfo.inputNum = null
			// 	 }
			// }
			// else{
			// 	data.scanInfo.inputNum = null
			// }
			// 退货数量就是条码数量
			if(data.checkPart==true){
				data.scanInfo.inputNum=0
			}else{
				data.scanInfo.inputNum = res.data.currentQty
			}

			data.scanInfo.picker = data.userName
			data.scanInfo.department = data.department
			data.scanInfo.remark = data.remark,
			data.scanInfo.costItem = data.costItem
			// return
			inputDialog.value.open()
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}
//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/qms/iqcOtherBoundRecord'
	})
}
const departmentSelect = (e) => {
	data.deportmentCode = e.value
}
//确定按钮
const handelSubmit = () => {
	console.log(data.scanInfo.inputNum)
	if (data.iqcOutScanListOther.length == 0) {
		uni.showToast({ title: t('stockManage.pleaseScanCode'), icon: "none" });
		return
	}
	if (data.department.length == 0) {
		uni.showToast({ title: t('JsInternational.chooseDept'), icon: "none" });
		return
	}
	let tepData = toRaw(data.iqcOutScanListOther)
	// if(tepData.length>1){
	// 	uni.showToast({ title: t('Common.onlyOneBarcode'), icon: "none" });
	// 	return
	// }
	let wmsBarcodeList = []
	let remarkArr = []
	let pickerArr = []
	let costItemArr = []
	let materialCode = ""
	tepData.forEach(x => {
		materialCode = x.materialCode
		console.log(x, '-----wmsBarcodeList-----')
		wmsBarcodeList.push({
			id: x.id,
			changeQty: x.inputNum,
			materialCode: x.materialCode
		})
		if (x.remark.length) {
			remarkArr.push(x.remark)
		}
		if (x.costItem.length) {
			costItemArr.push(x.costItem)
		}
		pickerArr.push(x.picker)

	});
	let parmes = {
		deportmentCode: data.deportmentCode,
		wmsBarcodeList: wmsBarcodeList,
		picker: pickerArr.join(','),
		remark: remarkArr.join(','),
		costItem: costItemArr.join(','),
		isIqc: 'Y',
		isGrn: data.selectId, //新添加的是否生成退回单
		materialCode: materialCode
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	iqcOutCommits(parmes).then(res => { //接口
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '粉碎简单生产退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			data.scanInfo = null
			//删除已提交的数据
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			store.dispatch('hardWare/resetIqcOutScanListOther')
			data.scanInfo = null
			data.scanValue = null
			data.allInputNum = null
			data.userName = ''
			data.remark = ''
			data.costItem = ''
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}

//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.iqcOutScanListOther.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.dispatch('hardWare/resetIqcOutScanListOther')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}

const checkboxAllChange = () => {
	data.checkAll = !data.checkAll
	if(data.checkAll==true){
		data.checkPart=false
	}
}
const checkboxPartChange = () => {
	data.checkPart = !data.	checkPart
	if(data.checkPart==true){
		data.checkAll=false
	}
}

//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.iqcOutScanListOther.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.dispatch('hardWare/resetIqcOutScanListOther')
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})

</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0rpx;
	bottom: 0rpx;
	width: 100%
}

.item-info-title {
	width: 100px !important;
}

.checkbox {
	display: flex;
	flex-direction: row;
	line-height: 100%;

	&-check {
		width: 10%;
		text-align: right;
		box-sizing: border-box;
		// margin-left: 10rpx;
	}

	&-spec {
		flex: 1;
		font-size: 28rpx;
		padding-left: 10rpx;
		line-height: 160%;
	}
}
</style>
